package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.UserFocusEntity;

public class UserFocusDAO {

	public List<UserFocusEntity> listByUserId(Connection conn, int user_id) throws SQLException {
		List<UserFocusEntity> list=new LinkedList<UserFocusEntity>();
		PreparedStatement ps=conn.prepareStatement("select * from user_focus where user_id=? order by add_time desc");
		ps.setInt(1, user_id);
		ResultSet rs=ps.executeQuery();
		while(rs.next()) {
			UserFocusEntity entity=fill(rs);
			list.add(entity);
		}
		return list;
	}

	private UserFocusEntity fill(ResultSet rs) throws SQLException {
		UserFocusEntity focusEntity=new UserFocusEntity();
		focusEntity.setId(rs.getInt("id"));
		focusEntity.setFriend_id(rs.getInt("friend_id"));
		focusEntity.setUser_id(rs.getInt("user_id"));
		focusEntity.setAdd_time(rs.getTimestamp("add_time"));
		return focusEntity;
	}

	public boolean insert(Connection conn, List<UserFocusEntity> list) throws SQLException {
		boolean b = false;
		conn.setAutoCommit(false);
		PreparedStatement ps = conn
				.prepareStatement("insert into user_focus(user_id,friend_id,add_time) values(?,?,?)");
		for (UserFocusEntity entity : list) {
			ps.setInt(1, entity.getUser_id());
			ps.setInt(2, entity.getFriend_id());
			ps.setTimestamp(3, entity.getAdd_time());
			ps.addBatch();
		}
		int[] count=ps.executeBatch();
		if (count.length > 0) {
			b = true;
		}
		conn.commit();
		return b;
	}

	public boolean deleteByUserId(Connection conn, int user_id) throws SQLException {
		PreparedStatement ps = conn.prepareStatement("delete from user_focus where user_id=?");
		ps.setInt(1, user_id);
		boolean b = ps.executeUpdate() > 0 ? true : false;
		return b;

	}

	public UserFocusEntity findByFocus(Connection conn,int user_id, int friend_id) throws SQLException {
		UserFocusEntity entity=null;
		PreparedStatement ps=conn.prepareStatement("select * from user_focus where user_id=? and friend_id = ?");
		ps.setInt(1, user_id);
		ps.setInt(2, friend_id);
		ResultSet rs=ps.executeQuery();
		if(rs.next()) {
			entity=fill(rs);
		}
		return entity;
	}

	public void deleteByFocus(Connection conn, int user_id, int friend_id) throws SQLException {
		PreparedStatement ps=conn.prepareStatement("delete from user_focus where user_id=? and friend_id = ?");
		ps.setInt(1, user_id);
		ps.setInt(2, friend_id);
		ps.executeUpdate();
		
	}

}
